/**
 * 科目成绩汇总交互功能
 * 文件名：subject-scores.js
 * 位置：static/users/js/subject-scores.js
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化科目成绩模块
    initSubjectScores();

    // 初始化搜索功能
    initScoreFilters();

    // 初始化工具提示
    initScoreTooltips();

    // 添加打印功能
    addPrintFunctionality();
});

/**
 * 科目成绩汇总交互功能
 */
function initSubjectScores() {
    // 系列展开/收起交互
    const seriesToggles = document.querySelectorAll('.series-toggle');

    seriesToggles.forEach(toggle => {
        toggle.addEventListener('click', function(e) {
            e.stopPropagation();
            const seriesItem = this.closest('.series-item');
            const isExpanding = this.getAttribute('aria-expanded') === 'false';

            // 更新图标
            const icon = this.querySelector('i');
            if (isExpanding) {
                icon.classList.remove('bi-chevron-down');
                icon.classList.add('bi-chevron-up');
                seriesItem.classList.add('expanded');
            } else {
                icon.classList.remove('bi-chevron-up');
                icon.classList.add('bi-chevron-down');
                seriesItem.classList.remove('expanded');
            }

            // 添加展开动画
            if (isExpanding) {
                const details = seriesItem.querySelector('.series-details');
                details.style.opacity = '0';
                details.style.transform = 'translateY(-10px)';

                setTimeout(() => {
                    details.style.transition = 'all 0.3s ease';
                    details.style.opacity = '1';
                    details.style.transform = 'translateY(0)';
                }, 50);
            }
        });
    });

    // 系列标题点击跳转
    const seriesHeaders = document.querySelectorAll('.series-header');
    seriesHeaders.forEach(header => {
        header.addEventListener('click', function(e) {
            // 如果点击的是切换按钮，不跳转
            if (e.target.closest('.series-toggle') || e.target.closest('.btn')) {
                return;
            }

            const seriesLink = this.querySelector('a[href*="score_list"]');
            if (seriesLink) {
                window.location.href = seriesLink.href;
            }
        });
    });

    // 成绩项点击跳转到详情页
    const recordItems = document.querySelectorAll('.record-item');
    recordItems.forEach(item => {
        item.addEventListener('click', function() {
            const recordId = this.getAttribute('data-record-id');
            if (recordId) {
                // 跳转到成绩详情页
                window.location.href = `/score/${recordId}/detail/`;
            }
        });

        // 添加悬停效果
        item.addEventListener('mouseenter', function() {
            this.style.cursor = 'pointer';
            this.style.background = 'linear-gradient(135deg, #f8fafc 0%, #f0f7ff 100%)';
        });

        item.addEventListener('mouseleave', function() {
            this.style.background = 'white';
        });
    });

    // 初始化系列项的动画
    initSeriesAnimations();
}

/**
 * 初始化系列项入场动画
 */
function initSeriesAnimations() {
    const seriesItems = document.querySelectorAll('.series-item');

    seriesItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateY(20px)';

        setTimeout(() => {
            item.style.transition = 'all 0.5s ease';
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
        }, 100 + (index * 100));
    });
}

/**
 * 搜索和过滤功能
 */
function initScoreFilters() {
    const searchInput = document.querySelector('.score-search-input');

    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            filterScores(searchTerm);
        });

        // 添加清除搜索按钮
        addClearSearchButton(searchInput);
    }
}

/**
 * 添加清除搜索按钮
 */
function addClearSearchButton(searchInput) {
    const clearBtn = document.createElement('button');
    clearBtn.type = 'button';
    clearBtn.className = 'btn btn-sm btn-outline-secondary position-absolute end-0 top-0 me-2 mt-2';
    clearBtn.innerHTML = '<i class="bi bi-x"></i>';
    clearBtn.style.display = 'none';
    clearBtn.addEventListener('click', function() {
        searchInput.value = '';
        searchInput.focus();
        filterScores('');
        this.style.display = 'none';
    });

    const searchContainer = searchInput.parentElement;
    searchContainer.style.position = 'relative';
    searchContainer.appendChild(clearBtn);

    searchInput.addEventListener('input', function() {
        clearBtn.style.display = this.value ? 'block' : 'none';
    });
}

/**
 * 过滤成绩显示
 */
function filterScores(searchTerm) {
    const subjectSections = document.querySelectorAll('.subject-section');
    let hasVisibleContent = false;

    subjectSections.forEach(section => {
        let sectionHasVisibleSeries = false;
        const seriesItems = section.querySelectorAll('.series-item');
        const emptySeries = section.querySelector('.empty-series');

        seriesItems.forEach(item => {
            const seriesName = item.querySelector('.series-name').textContent.toLowerCase();
            const recordNames = Array.from(item.querySelectorAll('.record-name'))
                .map(el => el.textContent.toLowerCase());

            const matchesSearch = seriesName.includes(searchTerm) ||
                                recordNames.some(name => name.includes(searchTerm));

            if (matchesSearch || searchTerm === '') {
                item.style.display = 'block';
                sectionHasVisibleSeries = true;
                hasVisibleContent = true;

                // 高亮匹配的文本
                highlightMatches(item, searchTerm);
            } else {
                item.style.display = 'none';
                removeHighlights(item);
            }
        });

        // 显示/隐藏科目部分
        if (sectionHasVisibleSeries || searchTerm === '') {
            section.style.display = 'block';
            if (emptySeries) emptySeries.style.display = 'block';
        } else {
            section.style.display = 'none';
            if (emptySeries) emptySeries.style.display = 'none';
        }
    });

    // 显示无结果提示
    showNoResultsMessage(!hasVisibleContent && searchTerm !== '');
}

/**
 * 高亮匹配的文本
 */
function highlightMatches(element, searchTerm) {
    if (!searchTerm) return;

    const textNodes = getTextNodes(element);
    textNodes.forEach(node => {
        const parent = node.parentNode;
        if (parent.classList && parent.classList.contains('highlight')) {
            return; // 已经高亮过了
        }

        const text = node.textContent;
        const regex = new RegExp(`(${escapeRegex(searchTerm)})`, 'gi');
        const newText = text.replace(regex, '<mark class="bg-warning">$1</mark>');

        if (newText !== text) {
            const newElement = document.createElement('span');
            newElement.innerHTML = newText;
            parent.replaceChild(newElement, node);
        }
    });
}

/**
 * 移除高亮
 */
function removeHighlights(element) {
    const highlights = element.querySelectorAll('mark.bg-warning');
    highlights.forEach(highlight => {
        const parent = highlight.parentNode;
        parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
        parent.normalize();
    });
}

/**
 * 获取元素中的所有文本节点
 */
function getTextNodes(element) {
    const textNodes = [];
    const walk = document.createTreeWalker(
        element,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    while (node = walk.nextNode()) {
        textNodes.push(node);
    }

    return textNodes;
}

/**
 * 转义正则表达式特殊字符
 */
function escapeRegex(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

/**
 * 显示无结果提示
 */
function showNoResultsMessage(show) {
    let noResultsMsg = document.querySelector('.no-results-message');
    const subjectScoresContainer = document.querySelector('.subject-scores-container');

    if (show && !noResultsMsg && subjectScoresContainer) {
        noResultsMsg = document.createElement('div');
        noResultsMsg.className = 'no-results-message text-center py-5';
        noResultsMsg.innerHTML = `
            <i class="bi bi-search display-4"></i>
            <h5 class="mt-3">未找到相关成绩记录</h5>
            <p class="text-muted">请尝试其他搜索关键词</p>
        `;

        subjectScoresContainer.parentNode.insertBefore(noResultsMsg, subjectScoresContainer);
    } else if (!show && noResultsMsg) {
        noResultsMsg.remove();
    }
}

/**
 * 初始化工具提示
 */
function initScoreTooltips() {
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    if (tooltipTriggerList.length > 0 && typeof bootstrap !== 'undefined') {
        const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                trigger: 'hover',
                delay: { show: 300, hide: 100 },
                placement: 'top'
            });
        });
    }
}

/**
 * 添加打印功能
 */
function addPrintFunctionality() {
    const printBtn = document.createElement('button');
    printBtn.className = 'btn btn-outline-secondary ms-2';
    printBtn.innerHTML = '<i class="bi bi-printer"></i> 打印成绩';
    printBtn.type = 'button';

    printBtn.addEventListener('click', function() {
        printScores();
    });

    const cardHeader = document.querySelector('.subject-scores-container')?.closest('.student-card')?.querySelector('.card-header');
    if (cardHeader) {
        const headerDiv = cardHeader.querySelector('.d-flex');
        if (headerDiv) {
            headerDiv.appendChild(printBtn);
        }
    }
}

/**
 * 打印成绩功能
 */
function printScores() {
    // 保存原始状态
    const originalTitle = document.title;
    const searchContainer = document.querySelector('.score-search-container');
    const buttons = document.querySelectorAll('.card-header .btn');

    // 设置打印标题
    document.title = `成绩汇总 - ${originalTitle}`;

    // 隐藏搜索框和按钮
    if (searchContainer) searchContainer.style.display = 'none';
    buttons.forEach(btn => btn.style.display = 'none');

    // 展开所有系列
    const collapsedSeries = document.querySelectorAll('.series-details.collapse:not(.show)');
    collapsedSeries.forEach(collapse => {
        collapse.classList.add('show');
    });

    // 触发打印
    window.print();

    // 恢复原始状态
    document.title = originalTitle;
    if (searchContainer) searchContainer.style.display = 'block';
    buttons.forEach(btn => btn.style.display = 'inline-block');

    // 恢复折叠状态
    collapsedSeries.forEach(collapse => {
        collapse.classList.remove('show');
    });
}

/**
 * 导出数据功能
 */
function exportScoresData() {
    const subjectSections = document.querySelectorAll('.subject-section');
    const exportData = [];

    subjectSections.forEach(section => {
        const subjectName = section.querySelector('.subject-title span.fw-semibold').textContent.replace('成绩', '');
        const seriesItems = section.querySelectorAll('.series-item');

        const subjectData = {
            subject: subjectName,
            series: []
        };

        seriesItems.forEach(seriesItem => {
            const seriesName = seriesItem.querySelector('.series-name').textContent;
            const recordItems = seriesItem.querySelectorAll('.record-item');

            const seriesData = {
                series: seriesName,
                records: []
            };

            recordItems.forEach(recordItem => {
                const recordName = recordItem.querySelector('.record-name').textContent;
                const score = recordItem.querySelector('.score-value').textContent;
                const date = recordItem.querySelector('.record-date').textContent;

                seriesData.records.push({
                    exam: recordName,
                    score: score,
                    date: date
                });
            });

            subjectData.series.push(seriesData);
        });

        exportData.push(subjectData);
    });

    // 创建下载链接
    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `成绩数据_${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

/**
 * 添加导出功能按钮
 */
function addExportFunctionality() {
    const exportBtn = document.createElement('button');
    exportBtn.className = 'btn btn-outline-success ms-2';
    exportBtn.innerHTML = '<i class="bi bi-download"></i> 导出数据';
    exportBtn.type = 'button';

    exportBtn.addEventListener('click', function() {
        exportScoresData();
    });

    const cardHeader = document.querySelector('.subject-scores-container')?.closest('.student-card')?.querySelector('.card-header');
    if (cardHeader) {
        const headerDiv = cardHeader.querySelector('.d-flex');
        if (headerDiv) {
            headerDiv.appendChild(exportBtn);
        }
    }
}

// 在DOM加载完成后添加导出功能
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        addExportFunctionality();
    }, 1000);
});

// 导出函数供其他脚本使用
window.SubjectScores = {
    initSubjectScores,
    initScoreFilters,
    filterScores,
    printScores,
    exportScoresData,
    addPrintFunctionality,
    addExportFunctionality
};

console.log('科目成绩汇总模块加载完成');